package com.shizhanzhe.zxbapp.customtask;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.Publish;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.pay.PayTaskActivity;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.widget.MyListView;
import com.shizhanzhe.zxbapp.widget.SignDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by zz9527 on 2018/11/8.
 */
public class PublishActivity extends AppCompatActivity {
    private List<LocalMedia> selectList = new ArrayList<>();
    //    private RecyclerView recyclerView;
//    private GridImageAdapter adapter;
    private int maxSelectNum = 3;
    private EditText total;
    private EditText everyprice;
    private EditText name;
    private EditText time;
    private Spinner spinner;
    private EditText content;
    private int type = 3;
    private ProgressDialog dialog;
    private RadioGroup rg;
    private MyListView lv;
    private PublishAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        ImmersionBar.with(this).statusBarColor(R.color.them)
                .fitsSystemWindows(true).init();
        initView();
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
//        recyclerView.setLayoutManager(manager);
//        adapter = new GridImageAdapter(this, onAddPicClickListener);
//        adapter.setList(selectList);
//        adapter.setSelectMax(maxSelectNum);
//        recyclerView.setAdapter(adapter);
//        adapter.setSelectMax(maxSelectNum);
//        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position, View v) {
//                if (selectList.size() > 0) {
//                    PictureSelector.create(PublishActivity.this).externalPicturePreview(position, selectList);
//                }
//            }
//        });


        findViewById(R.id.btn_publish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(name.getText().toString())
                        && !TextUtils.isEmpty(total.getText().toString()) && !TextUtils.isEmpty(everyprice.getText().toString())
                        && !TextUtils.isEmpty(time.getText().toString())) {
                    if (Integer.parseInt(total.getText().toString())<UserBean.subnum ){
                        Toast.makeText(PublishActivity.this, "份数最低为"+UserBean.subnum, Toast.LENGTH_SHORT).show();
                        return;
                    }else if( time.getText().toString().equals("0")) {
                        Toast.makeText(PublishActivity.this, "时间不能为0", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(everyprice.getText().toString()) <= Double.parseDouble(UserBean.subprice)) {
                        Toast.makeText(PublishActivity.this, "每份奖励金额最低为"+ UserBean.subprice+"元", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (list.get(list.size() - 1).getSelectList().size() == 0) {
                        Toast.makeText(PublishActivity.this, "最后一步请添加示例图片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    for (Publish p : list
                            ) {
                        if ("".equals(p.getContent())) {
                            Toast.makeText(PublishActivity.this, "步骤内容不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    Intent intent = new Intent(PublishActivity.this, PayTaskActivity.class);
                    intent.putExtra("total", Integer.parseInt(total.getText().toString()) * Double.parseDouble(everyprice.getText().toString()));
                    startActivityForResult(intent, 110);
                } else {
                    Toast.makeText(PublishActivity.this, "发布信息请填写完整", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    List<Publish> list = new ArrayList<>();

    private void initView() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在提交...");
        lv = findViewById(R.id.lv);
        total = findViewById(R.id.task_total);
        everyprice = findViewById(R.id.task_everyprice);
        total.setText(UserBean.subnum+"");
        everyprice.setText(UserBean.subprice);
        name = findViewById(R.id.task_name);
        time = findViewById(R.id.task_time);
//        content = findViewById(R.id.task_content);
        spinner = findViewById(R.id.task_spinner);
        rg = findViewById(R.id.rg);
        list = new ArrayList<>();
        list.add(new Publish("", "^", new ArrayList<LocalMedia>()));
        adapter = new PublishAdapter(this, list);
        lv.setAdapter(adapter);
        findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.add(new Publish("", "^", new ArrayList<LocalMedia>()));
                adapter.notifyDataSetChanged();
            }
        });
    }

//    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
//        @Override
//        public void onAddPicClick() {
//            // 进入相册 以下是例子：不需要的api可以不写
//            PictureSelector.create(PublishActivity.this)
//                    .openGallery(PictureMimeType.ofAll())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                    .maxSelectNum(maxSelectNum - selectList.size())// 最大图片选择数量
//                    .minSelectNum(1)// 最小选择数量
//                    .imageSpanCount(3)// 每行显示个数
//                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
//                    .previewImage(true)// 是否可预览图片
//                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
//                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                    .selectionMedia(selectList)// 是否传入已选图片
//                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
//
//        }
//
//    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 图片选择结果回调
            selectList = PictureSelector.obtainMultipleResult(data);
            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
            list.get(requestCode).getSelectList().addAll(selectList);
//            adapter.setImgList(selectList);
            adapter.notifyDataSetChanged();

        } else if (resultCode == 110) {
            dialog.show();
            ordersn=data.getStringExtra("ordersn");
            uploadImg();

        }
    }
    String ordersn = "";
    private StringBuilder imgs = new StringBuilder();
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    final Handler handler = new Handler();
    private final OkHttpClient client = new OkHttpClient();
    private String tvcontent = "";

    private void uploadImg() {
        // mImgUrls为存放图片的url集合
        int count = 0;
        for (int k = 0; k < list.size(); k++) {
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            final List<LocalMedia> selectList = list.get(k).getSelectList();
            tvcontent += list.get(k).getContent() + "^";
            count++;
            if (selectList.size() == 0) {

            } else {

                for (LocalMedia b : selectList
                        ) {
                    File f = new File(b.getPath());
                    if (f != null) {
                        builder.addFormDataPart("image[]", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
                    }
                }
                MultipartBody requestBody = builder.build();
                //构建请求
                Request request = new Request.Builder()
                        .url(Path.PUBLISHSUB())//地址
                        .post(requestBody)//添加请求体
                        .build();

                final int finalCount = count;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
//                            Toast.makeText(PublishActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
//                    imgs.append(response.body().string() + "^");
                        list.get(finalCount - 1).setImgurl(response.body().string() + "^");
//                        Log.i("__________", finalCount + "_" + list.get(finalCount - 1).getImgurl());
                        if (finalCount == list.size()) {
                            for (Publish p : list
                                    ) {
                                imgs.append(p.getImgurl());
                            }
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    publish();
                                }
                            });
                        }
                    }

                });
            }

        }

    }

    int canyu = 0;

    private void publish() {
        Log.i("_________", tvcontent + "___" + imgs+"________"+ordersn);
        switch ((String) spinner.getSelectedItem()) {
            case "下载":
                type = 1;
                break;
            case "注册":
                type = 2;
                break;
            case "其他":
                type = 3;
                break;
            default:
                break;
        }
        switch (rg.getCheckedRadioButtonId()) {
            case R.id.rg_all:
                canyu = 0;
                break;
            case R.id.rg_vip:
                canyu = 1;
                break;
            default:
                break;
        }
        OkHttpDownloadJsonUtil.downloadJson(this, Path.PUBLISH2(UserBean.uid, type, name.getText().toString(), "", total.getText().toString(), everyprice.getText().toString(), time.getText().toString(), "", canyu,ordersn), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
//                Log.i("______创建", json);
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        JSONObject object = new JSONObject(json);
                        if (object.optString("status").equals("1")) {
                            uploadMsg(object.optInt("taskid"));
                        } else {
                            Toast.makeText(PublishActivity.this, "任务创建失败", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(PublishActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void uploadMsg(int taskid) {
//        Log.i("_________", tvcontent + "___" + imgs);
        OkHttpDownloadJsonUtil.downloadJson(this, Path.PUBLISHMSG(taskid, tvcontent, imgs.toString()), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                dialog.dismiss();
                try {
//                    Log.i("______提交", json);
                    JSONObject object = new JSONObject(json);
                    if (object.optString("status").equals("1")) {
                        final SignDialog dialog = new SignDialog(PublishActivity.this);
                        dialog.setListener(new SignDialog.SignListener() {
                            @Override
                            public void checktrue() {
                                dialog.dismiss();
                                startActivity(new Intent(PublishActivity.this, ApprovalActivity.class));
                                finish();
                            }
                        });
                        dialog.show();
                        dialog.showMsg("任务提交成功!");
                        PictureFileUtils.deleteCacheDirFile(PublishActivity.this);

                    } else {
                        Toast.makeText(PublishActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy(); //必须调用该方法，防止内存泄漏
    }
}
